package online.sixfish.doubao.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import online.sixfish.common.dto.UserDetail;
import online.sixfish.common.exception.ApiAsserts;
import online.sixfish.common.pojo.User;
import online.sixfish.doubao.enumration.RoleEnum;
import online.sixfish.doubao.mapper.UmsUserMapper;
import online.sixfish.doubao.model.dto.LoginDTO;
import online.sixfish.doubao.service.AdminService;
import online.sixfish.common.utils.JwtUtils;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service
public class AdminServiceImpl implements AdminService {
    @Resource
    UmsUserMapper umsUserMapper;
    @Resource
    PasswordEncoder passwordEncoder;
    @Override
    public String login(LoginDTO loginDTO) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<User>()
                .eq("username", loginDTO.getUsername());
        User user = umsUserMapper.selectOne(queryWrapper);
        boolean isMatch = passwordEncoder
                .matches(loginDTO.getPassword(), user.getPassword());
        if(!isMatch){
            ApiAsserts.fail("账号密码不匹配！");
        }
        if(!user.getRoleId().equals(RoleEnum.ADMIN.getId())){
            ApiAsserts.fail("非管理员账号！");
        }
        return JwtUtils.createToken(new UserDetail(user));
    }
}
